package gx.web.controller;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import gx.entity.Category;
import gx.entity.Customer;
import gx.entity.Manager;
import gx.entity.Product;
import gx.entity.Sale;
import gx.entity.SaleItem;
import gx.entity.common.Page;
import gx.service.CategoryService;
import gx.service.CustomerService;
import gx.service.ProductService;
import gx.service.SaleItemService;
import gx.service.SaleService;


@Controller
@RequestMapping("/mng/sale")
public class SaleController {
	
	@Autowired
	private SaleService saleService;
	
	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private SaleItemService saleItemService;
	
	//显示所以销售信息
	@RequestMapping("/list.jhtml")
	public ModelAndView list(@RequestParam(name = "size", defaultValue = "10") int size,
			@RequestParam(name = "number", defaultValue = "1") int number){
		ModelAndView mav = new ModelAndView("/mng/sale/list");
		Page<Sale> page = saleService.findByStatus(size, number, 0, 1,2);
		mav.addObject("page", page);
		return mav;
	}
	
	// 动态查询
		@RequestMapping("/find.jhtml")
		public ModelAndView find(@RequestParam(name = "size", defaultValue = "10") int size,
				@RequestParam(name = "number", defaultValue = "1") int number, Integer status, String startDate,
				String endDate) throws ParseException {
			// 离线查询条件对象 "from Sale"
			DetachedCriteria dc = DetachedCriteria.forClass(Sale.class);
			DetachedCriteria dc2 = DetachedCriteria.forClass(Sale.class);
			DetachedCriteria dc3 = DetachedCriteria.forClass(Sale.class);
			// "from Purchase where status?"
			if (status != null && status.intValue() >= 0) {
				dc.add(Property.forName("status").eq(status)); // eq: 等于
				dc2.add(Property.forName("status").eq(status));
				dc3.add(Property.forName("status").eq(status));
			} else {
				Criterion c = Restrictions.or(Restrictions.eq("status", 0), Restrictions.eq("status", 1),Restrictions.eq("status", 2));
				dc.add(c);
				dc2.add(c);
				dc3.add(c);
			}
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

			// "from sale where status=? and pur_date>? "
			if (null != startDate && !"".equals(startDate)) {
				dc.add(Property.forName("sale_date").ge(df.parse(startDate)));// ge:大于等于
				dc2.add(Property.forName("sale_date").ge(df.parse(startDate)));
				dc3.add(Property.forName("sale_date").ge(df.parse(startDate)));
			}

			// "from sale where status=? and pur_date>? and pur_date<?"
			if (null != endDate && !"".equals(endDate)) {
				dc.add(Property.forName("sale_date").le(df.parse(endDate)));// le:
																			// 小于等于
				dc2.add(Property.forName("sale_date").ge(df.parse(startDate)));
				dc3.add(Property.forName("sale_date").ge(df.parse(startDate)));
			}

			dc.addOrder(Order.desc("id"));
			dc2.setProjection(Projections.count("id"));
			dc3.setProjection(Projections.count("id"));

			Page<Sale> page = saleService.findByCriteria(size, number, dc, dc2,dc3);

			ModelAndView mav = new ModelAndView("/mng/sale/list");
			mav.addObject("page", page);

			return mav;
		}
		
		//出单功能
		@RequestMapping("/place.jhtml")
		public String place(Integer id) {
			Sale sale = saleService.get(id);
			sale.setStatus(1);// 状态已出单
			saleService.update(sale);
			return "redirect:/mng/sale/list.jhtml";
		}
		//出库功能
		@RequestMapping("/iuku.jhtml")
		public String iuku(Integer id) {
			Sale sale = saleService.get(id);
			sale.setStatus(2);// 状态已出库
			saleService.update(sale);
			List<SaleItem> items=saleItemService.findBySaleId(id);
			int oldnum;//商品表中的原来数量
			int newnum;//商品出库后的新数量，原来数量必须大于出库的数量。在销售订单制定的时候就预判的。
			Integer[] p_id = new Integer[items.size()];
			Integer[] p_num = new Integer[items.size()];
			for(int i=0;i<items.size();i++){
				p_id[i] = items.get(i).getProduct().getId();
				p_num[i] = items.get(i).getNum();
				Product product = productService.get(p_id[i]);
				oldnum=product.getNum();
//				if(oldnum<p_num[i]){
//					
//				}
//				else {
					newnum=oldnum-p_num[i];
					product.setNum(newnum);
					productService.update(product);
			//	}
				
			}
			
			
			
			return "redirect:/mng/sale/list.jhtml";
		}
		
		
		//新增销售订单页面预加载功能
		
		@RequestMapping("/toAdd.jhtml")
		public ModelAndView toAdd() {
			ModelAndView mav = new ModelAndView("/mng/sale/add");
			// 客户
			List<Customer> custList = customerService.findAll();
			mav.addObject("custList", custList);

			// 商品分类
			List<Category> cateList = categoryService.findAll();
			mav.addObject("cateList", cateList);

			// sn序列号
			StringBuffer sb = new StringBuffer("CG");
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			mav.addObject("sn", sb.append(sdf.format(date)).toString());

			return mav;
		}
		
		//新增销售订单
		@RequestMapping("/add.jhtml")
		public String add(int pay_type, String sale_date, String remark, String sn,
				Integer cust_id, Integer[] p_id, Integer[] p_num,Integer num,
				BigDecimal[] sale_price, HttpSession session) throws ParseException {

			Manager mgr = (Manager) session.getAttribute("curr_mgr"); // 制单人信息

			Sale sale = new Sale(); // 销售订单项
			sale.setManager(mgr);
			sale.setPay_type(pay_type); // 支付类型 0:全款 1:欠款
			if (sale_date != null && !"".equals(sale_date)) {
				sale.setSale_date(new SimpleDateFormat("yyyy-MM-dd").parse(sale_date));
			}
			sale.setRemark(remark); // 备注
			sale.setSn(sn); // 销售订单编号
			sale.setStatus(0); // 默认为草稿
			sale.setCustomer(customerService.load(cust_id)); // 设置所属的供应商

			// 采购项
			ArrayList<SaleItem> items = new ArrayList<SaleItem>();

			int length = p_id == null ? 0 : p_id.length; // 采购订单项
			//Integer oldnum=num;
			for (int i = 0; i < length; i++) {
				
				Integer id = p_id[i];
		//		Product product = productService.get(p_id[i]);
					SaleItem item = new SaleItem(); // 采购订单项对象
					item.setNum(p_num[i]); // 数据
					item.setPrice(sale_price[i]); // 价格
					item.setProduct(productService.load(id)); // 设置所属商品
					item.setSale(sale);// 隶属采购订单

					boolean exists = false;
					for (SaleItem temp : items) {
						if (id.intValue() == temp.getProduct().getId().intValue()) {
							temp.setNum(temp.getNum() + p_num[i]);
							exists = true;
							break;
						}
					}
	
					if (!exists) {
						items.add(item);
					}
				
				sale.setItemList(items);
				// 计算总价
				BigDecimal totals = new BigDecimal(0);
				for (SaleItem temp : items) {
					totals = totals.add(temp.getPrice().multiply(
							new BigDecimal(temp.getNum())));
				}
				sale.setCost(totals); // 采购订单中总额
				saleService.save(sale);
		//	}//1
		}
			return "redirect:/mng/sale/list.jhtml";
		}
		
		//删除草稿下的销售订单
		@RequestMapping("/delete.jhtml")
		public String delete(Integer id) {
			saleService.delete(id);
			return "redirect:/mng/sale/list.jhtml";
		}

		// 编辑加载数据功能
		@RequestMapping("/detail.jhtml")
		public ModelAndView detail(Integer id) {
			ModelAndView mav = new ModelAndView("/mng/sale/detail");
			// 获得采购订单
			Sale sale = saleService.get(id);

			// 采购订单编号
			mav.addObject("sn", sale.getSn());

			// 客户
			List<Customer> custList = customerService.findAll();
			mav.addObject("custList", custList);

			// 商品分类
			List<Category> cateList = categoryService.findAll();
			mav.addObject("cateList", cateList);

			mav.addObject("sale",sale);
			
			mav.addObject("sale_list",sale.getItemList());//采购项List
			return mav;
		}
		// 编辑加载数据功能
				@RequestMapping("/detail2.jhtml")
				public ModelAndView detail2(Integer id) {
					ModelAndView mav = new ModelAndView("/mng/sale/detail2");
					// 获得采购订单
					Sale sale = saleService.get(id);

					// 采购订单编号
					mav.addObject("sn", sale.getSn());

					// 客户
					List<Customer> custList = customerService.findAll();
					mav.addObject("custList", custList);

					// 商品分类
					List<Category> cateList = categoryService.findAll();
					mav.addObject("cateList", cateList);

					mav.addObject("sale",sale);
					
					mav.addObject("sale_list",sale.getItemList());//采购项List
					return mav;
				}
		//修改功能
	    @RequestMapping("/edit.jhtml")
	    public String edit(int id,int pay_type, String sale_date, String remark, String sn, 
				Integer cust_id, Integer[] p_id,Integer[] p_num,
				BigDecimal[] sale_price, HttpSession session) throws ParseException{
	    	Manager mgr = (Manager) session.getAttribute("curr_mgr"); // 制单人信息

	    	Sale sale = saleService.get(id); // 或得采购订单项
	    	sale.setManager(mgr); //制单人
	    	sale.setPay_type(pay_type); // 支付类型 0:全款 1:欠款
			if (sale_date != null && !"".equals(sale_date)) {
				sale.setSale_date(new SimpleDateFormat("yyyy-MM-dd").parse(sale_date));
			}
			sale.setRemark(remark); // 备注
			sale.setSn(sn); // 采购订单编号
			sale.setStatus(0); // 默认为草稿
			sale.setCustomer(customerService.load(cust_id)); // 设置所属的客户

			// 采购项
			ArrayList<SaleItem> items = new ArrayList<SaleItem>();

			//通过id查询所以采购订单项
			List<SaleItem> custitem_list = saleItemService.findBySaleId(id);
			
			for(int i = 0; i < custitem_list.size();i++){
				
				saleItemService.delete(custitem_list.get(i));
				
			}
			int length = p_id == null ? 0 : p_id.length; // 采购订单项
			for (int i = 0; i < length; i++) {
				//删除
				Integer pitem_id = p_id[i];
				SaleItem item = new SaleItem(); // 采购订单项对象
				item.setNum(p_num[i]); // 数据
				item.setPrice(sale_price[i]); // 价格
				item.setProduct(productService.load(pitem_id)); // 设置所属商品
				item.setSale(sale);// 隶属采购订单

				boolean exists = false;
				for (SaleItem temp : items) {
					if (pitem_id.intValue() == temp.getProduct().getId().intValue()) {
						temp.setNum(temp.getNum() + p_num[i]);
						exists = true;
						break;
					}
				}

				if (!exists) {
					items.add(item);
				}
			}
			sale.setItemList(items);
			// 计算总价
			BigDecimal totals = new BigDecimal(0);
			for (SaleItem temp : items) {
				totals = totals.add(temp.getPrice().multiply(new BigDecimal(temp.getNum())));
			}
			sale.setCost(totals); // 采购订单中总额
			saleService.update(sale);
	       return "redirect:/mng/sale/list.jhtml";
	    }
		



}
